package colicious.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import colicious.domain.Order;



public class JdbcOrderDao extends SimpleJdbcDaoSupport implements OrderDao {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	public List<Order> getOrderList() {
	
		logger.info("Getting Orders!");
		List<Order> orders = getSimpleJdbcTemplate().query(
				"select id, type, status, cxlCode, price from orders",
				new OrderMapper());
		
		return orders;
	}

	public void saveOrder(Order ord) {
		logger.info("Saving order: " + ord.getId());
		int count = getSimpleJdbcTemplate().update("update orders set type = :type, status = :status, cxlCode = :cxlCode, price = :price where id = :id",
		
		new MapSqlParameterSource()
			.addValue("type", ord.getPrice())
			.addValue("status", ord.getStatus())
			.addValue("cxlCode", ord.getCxlCode())
			.addValue("price", ord.getPrice())
			.addValue("id", ord.getId()));
		logger.info("Rows affected: " + count);
	}

	private static class OrderMapper implements ParameterizedRowMapper<Order> {
	
		public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
		
			Order ord = new Order();
			ord.setId(rs.getInt("id"));
			ord.setType(rs.getString("type"));
			ord.setStatus(rs.getString("status"));
			ord.setCxlCode(rs.getString("cxlCode"));
			ord.setPrice(new Double(rs.getDouble("price")));
			return ord;
		}
	}
}